package com.service.impl;

import com.controller.PaginationSupport;
import com.entity.Department;
import com.entity.Employee;
import com.entity.Salary;
import com.form.Message;
import com.form.SalaryInfoForAdmin;
import com.mapper.*;
import com.service.SalaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.util.List;

@Service
public class SalaryServiceImpl implements SalaryService {
    @Autowired
    SalaryMapper salaryMapper;
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    LevelMapper leveMapper;
    @Autowired
    PerformanceMapper performanceMapper;
    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    PerformanceLevelMapper performanceLevelMapper;

    public int count() {
        return salaryMapper.countOfSalarys();
    }

    @Override
    public PaginationSupport<SalaryInfoForAdmin> checkSalarys(int pageNo, int pageSize) {
        int totalcount = count();
        int startIndex = PaginationSupport.convertFromPageToStartIndex(pageNo, pageSize);
        List<SalaryInfoForAdmin> salarys = salaryMapper.findPage(startIndex, pageSize);
        PaginationSupport<SalaryInfoForAdmin> salaryList = new PaginationSupport<SalaryInfoForAdmin>(salarys, totalcount,
                pageSize, startIndex);
        return salaryList;
    }

    @Override
    public Message checkCurrentMonthPay(String username) {
        Employee employee = employeeMapper.getEmployeeByUername(username);
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取当前月份
        int currentMonth = currentDate.getMonthValue();
        // 获取当前年份
        int currentYear = Year.now().getValue();
        Salary salary = salaryMapper.checkCurrentMonthPay(employee.getEmployeeId(), currentYear, currentMonth);
        if (salary == null) {
            return new Message(1, "Current month don`t pay salary.");
        }
        return new Message(0, "Current month have paid salary.");
    }

    @Override
    public SalaryInfoForAdmin addSalary(String username, String performance) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 将LocalDate转换为Timestamp
        Timestamp currentTimestamp = Timestamp.valueOf(currentDate.atStartOfDay());
        // 获取当前年份
        int currentYear = currentDate.getYear();


        //获取当前员工信息 和 当前员工部门信息
        Employee employee = employeeMapper.getEmployeeByUername(username);
        Department department = departmentMapper.findDepartmentById(employee.getDepartmentId());

        //插入绩效表现
        int status = performanceMapper.addPerformance(employee.getEmployeeId(), performance, currentTimestamp);

        //计算岗位工资  岗位工资=岗位权重*部门基础工资
        double positionWeight = leveMapper.getPositionWeightByLevelId(employee.getLevelId());//获取岗位权重
        double positionSalary = positionWeight * department.getBasicSalary(); //岗位工资

        //计算工龄工资  工龄工资=（当前年-入职年*0.08*部门基础工资
        LocalDateTime employeeTime = employee.getEmployTime().toLocalDateTime();  // 将Timestamp转换为LocalDateTime
        LocalDate localDate = employeeTime.toLocalDate();    // 将LocalDateTime转换为LocalDate
        int employeeYear = employeeTime.getYear();
        double senioritySalary = (currentYear - employeeYear) * 0.08 * department.getBasicSalary();//工龄工资

        //计算绩效工资 绩效等级表中对应的绩效工资
        double performanceSalary = performanceLevelMapper.getPerformanceSalaryByLevel(performance);

        //计算津贴 津贴来源复杂，直接按照每人300算
        double allowance = 300;
        //计算总工资
        double totalSalaryAmount = senioritySalary + performanceSalary + positionSalary + allowance;
        //计算税务
        double taxation = calculateTaxation(totalSalaryAmount, employee.getEmployeeId(), currentYear);
        //本月实际收入 = 本月收入-本月收税-五险一金
        double actualPayAmount = totalSalaryAmount - taxation - 800;

        //添加工资记录
        Salary salary = new Salary();
        salary.setAllowance(300);
        salary.setPerformanceSalary(performanceSalary);
        salary.setPositionSalary(positionSalary);
        salary.setSenioritySalary(senioritySalary);
        salary.setTotalSalaryAmount(totalSalaryAmount);
        salary.setTaxation(taxation);
        salary.setActualPayAmount(actualPayAmount);
        salary.setPaymentDate(currentTimestamp);
        salary.setEmployeeId(employee.getEmployeeId());
        int status2 = salaryMapper.addSalary(salary);

        //将工资记录转成给管理员看的形式
        SalaryInfoForAdmin salaryInfoForAdmin = new SalaryInfoForAdmin();
        salaryInfoForAdmin.setAllowance(300);
        salaryInfoForAdmin.setPerformanceSalary(performanceSalary);
        salaryInfoForAdmin.setPositionSalary(positionSalary);
        salaryInfoForAdmin.setSenioritySalary(senioritySalary);
        salaryInfoForAdmin.setTotalSalaryAmount(totalSalaryAmount);
        salaryInfoForAdmin.setTaxation(taxation);
        salaryInfoForAdmin.setActualPayAmount(actualPayAmount);
        salaryInfoForAdmin.setPaymentDate(currentTimestamp);
        salaryInfoForAdmin.setFullName(employee.getFullname());
        return salaryInfoForAdmin;
    }

    @Override
    public PaginationSupport<SalaryInfoForAdmin> findSalaryByKeys(String keys, int pageNo, int pageSize) {
        int totalcount = salaryMapper.getCountOfSalaryByKeys(keys);
        int startIndex = PaginationSupport.convertFromPageToStartIndex(pageNo, pageSize);
        List<SalaryInfoForAdmin> salarys = salaryMapper.findPageByKeys(keys, startIndex, pageSize);
        PaginationSupport<SalaryInfoForAdmin> salaryList = new PaginationSupport<SalaryInfoForAdmin>(salarys, totalcount,
                pageSize, startIndex);
        return salaryList;
    }

    @Override
    public PaginationSupport<Salary> findSalaryByYearAndMonth(long employeeId, int year, int month,
                                                              int pageNo, int pageSize) {
        int totalCount = salaryMapper.getCountOfSalaryByYearAndMonth(employeeId,year,month);
        int startIndex = PaginationSupport.convertFromPageToStartIndex(pageNo,pageSize);
        List<Salary> salaryList = salaryMapper.findPageByYearAndMonth(employeeId,year,month,startIndex,pageSize);
        PaginationSupport<Salary> salarys = new PaginationSupport<Salary>(salaryList,totalCount,pageSize,pageNo);
        return salarys;
    }

    @Override
    public PaginationSupport<Salary> findSalaryByYear(long employeeId, int year, int pageNo, int pageSize) {
        int totalCount=salaryMapper.countOfYear(employeeId,year);
        int startIndex=PaginationSupport.convertFromPageToStartIndex(pageNo,pageSize);
        List<Salary> salaryList = salaryMapper.findPageByYear(employeeId,year,startIndex,pageSize);
        PaginationSupport<Salary> salarys=new PaginationSupport<Salary>(salaryList,totalCount,pageSize,startIndex);
        return salarys;
    }

    @Override
    public PaginationSupport<Salary> findSalaryByMonth(long employeeId, int month, int pageNo, int pageSize) {
        int totalCount=salaryMapper.countOfMonth(employeeId,month);
        int startIndex=PaginationSupport.convertFromPageToStartIndex(pageNo,pageSize);
        List<Salary> salaryList = salaryMapper.findPageByMonth(employeeId,month,startIndex,pageSize);
        PaginationSupport<Salary> salarys=new PaginationSupport<Salary>(salaryList,totalCount,pageSize,startIndex);
        return salarys;
    }

    private double calculateTaxation(double totalSalaryAmount, long employeeId, int currentYear) {
        //个人所得税起征点 = 本年累计收入 - （法定扣除项（5000）+ 五险一金（800） + 房贷扣除（1000） + 赡养老人（2000））*本年发放工资次数
        List<Double> salarys = salaryMapper.getTotalSalarysOfThisYear(employeeId, currentYear);
        double totalSalaryOfThisYear = totalSalaryAmount; //本年累计收入
        for (double salary : salarys) {
            totalSalaryOfThisYear += salary;
        }
        int count = salarys.size() + 1;//本年发放工资次数

        //计算个人所得税起征点
        double tax = totalSalaryOfThisYear - (5000 + 800 + 1000 + 2000) * count;

        //存储税务
        double taxation;

        //根据预算率和速算扣除数算出税务
        if (tax <= 0) {
            taxation = 0;
        } else if (tax < 36000) {
            taxation = totalSalaryOfThisYear * 0.03;
        } else if (tax < 144000) {
            taxation = totalSalaryOfThisYear * 0.10 - 2520;
        } else if (tax < 300000) {
            taxation = totalSalaryOfThisYear * 0.2 - 16920;
        } else if (tax < 420000) {
            taxation = totalSalaryOfThisYear * 0.25 - 31920;
        } else if (tax < 660000) {
            taxation = totalSalaryOfThisYear * 0.3 - 52920;
        } else if (tax < 960000) {
            taxation = totalSalaryOfThisYear * 0.35 - 85920;
        } else {
            taxation = totalSalaryOfThisYear * 0.45 - 181920;
        }
        return taxation;
    }
}
